package com.cn.demo4.servlet.admin.product;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.PageModel;
import com.cn.demo4.model.ProductModel;
import com.cn.demo4.service.IProductService;
import com.cn.demo4.service.impl.ProductServiceImpl;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 产品控制后台
 */
@WebServlet("/admin/product/findAll")
public class ProductFindAllServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        /**
         * 模糊查询
         * 得到前台传过来的数据
         */
        String name = req.getParameter("name");
        String houseName = req.getParameter("houseName");
        String startPrice = req.getParameter("startPrice");
        String endPrice = req.getParameter("endPrice");
        String status = req.getParameter("status");
        status = status == null ? "-1" : status;
        //分页数据
        String curPage = req.getParameter("curPage");
        String pageSize = req.getParameter("pageSize");

        //封装数据
        ProductModel productModel = new ProductModel();
        productModel.setHouseName(houseName);
        productModel.setName(name);
        productModel.setStatus(Tool.stringToInt(status));
        productModel.setStartPrice(Tool.stringToDouble(startPrice));
        productModel.setEndPrice(Tool.stringToDouble(endPrice));
        //实例化分页对象
        PageModel pageModel = new PageModel();
        pageModel.setCurPage(Tool.toCurPage(curPage));
        pageModel.setPageSize(Tool.toPageSize(pageSize));
        productModel.setPageModel(pageModel);

        //2.调用服务逻辑层
        IProductService iProductService = new ProductServiceImpl();
        //3.得到所有数据
        List<ProductModel> list = iProductService.findAll(productModel);
        int count = iProductService.getCount(productModel);
        //返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list);
        jsonObject.put("count", count);
        resp.getWriter().println(jsonObject);
    }
}
